package cn.edu.ctbu.test.api;

import cn.edu.ctbu.test.core.PageUtils;
import cn.edu.ctbu.test.domain.Sc;
import cn.edu.ctbu.test.service.ScService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Slf4j
@RestController // RestController只能返回数据
@NoRepositoryBean
@RequestMapping("/api/sc")
public class ScRestController {
    @Autowired
    ScService scService;

    @GetMapping("/list")
    public List<Sc> getAll(){
        List<Sc> scs=scService.findAll();

        return  scs;
    }


    /**
     * 分页读取全部内容
     * @return
     */
    @GetMapping("/getbypageSc")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "condition",defaultValue = "") Long condition)   {

        //按id排倒序
        Sort sort= Sort.by(Sort.Direction.ASC,"studentId");

        Page<Sc> scPage;

        if(ObjectUtils.isEmpty(condition)){
            Pageable pageable = PageRequest.of(page,size,sort);
            scPage= scService.findAll(pageable);
        }else {
            Sc sc = new Sc();
            sc.setStudentId(condition);

            Pageable pageable = PageRequest.of(0, 10, sort);

            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("condition", ExampleMatcher.GenericPropertyMatchers.contains());

            Example<Sc> example = Example.of(sc, matcher);

            scPage = scService.findAll(example, pageable);
        }

        PageUtils pageUtils=new PageUtils(scPage.getContent(),scPage.getTotalElements());

        return pageUtils;


    }



    @GetMapping("/get/{studentId}")
    public Sc get(@PathVariable Long id){

        Sc sc=scService.getById(id);

        return  sc;//把id返回到客户端
    }


    /**
     * 以下为增删改查
     * @param
     * @return
     */

    @PostMapping("/insert") //添加人员不用返回人员，返回成功或者失败就可以了
    public Sc insert(Sc sc){
        Sc sc1=scService.insert(sc);

        return sc1;
    }

    @DeleteMapping("/delete/{studentId}")
    public void delete(@PathVariable Long studentId){

        scService.delete(studentId);
    }

    @PutMapping("/update")
    public Sc update(Sc sc){

        //读取旧学生数据
        Sc oldstudent=scService.getById(sc.getStudentId());

        sc=scService.update(sc);

        return sc;
    }
    
    
}
